from django.http import StreamingHttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_GET
from langchain_community.llms.tongyi import Tongyi
from langchain_core.example_selectors import BaseExampleSelector
from rest_framework.views import APIView
from rest_framework.response import Response
from dashscope import Generation


# Create your views here.


def abc(resp):
    for r in resp:
        if r.status_code == 200:
            data = r.output.choices[0].message.content
            yield f"data:{data}\n\n"
        else:
            return 'on message'


@require_GET
def StreamingResp(request):
    question = request.GET.get('question')
    msgs = [{'role': 'user', 'content': question}]

    resp = Generation.call(
        model='qwen-turbo',
        messages=msgs,
        result_format='message',
        stream=True,
        incremental_output=True
    )
    response = StreamingHttpResponse(abc(resp), content_type="text/event-stream")
    response["Cache-Control"] = "no-cache"
    return response




class MySelector(BaseExampleSelector):
    def __init__(self, examples: list[dict[str, str]]) -> None:
        self.examples = examples

    def add_example(self, example: dict[str, str]) -> None:
        self.examples.append(example)

    def select_examples(self, input_variables: dict[str, str]) -> list[dict]:
        input_value = input_variables["ask1"]
        select_examples = []
        for ex in self.examples:
            example_input = ex["input"]
            if input_value in example_input:
                select_examples.append(ex)
        return select_examples


def bcd(resp):
    for r in resp:
        if r:
            print(r+"-----")
            yield f"data:{r}\n\n"
        else:
            return "no message"


@require_GET
def dolangchainstream(request):
    ask = request.GET.get("question")

    exs = [
        {"input": "流感症状", "output": "发烧、咳嗽、喉咙痛、身体酸痛。"},
        {"input": "糖尿病治疗", "output": "饮食控制、运动、药物"},
        {"input": "新冠肺炎症状", "output": "发烧、咳嗽、疲劳、味觉或嗅觉丧失。"},
        {"input": "糖尿病症状", "output": "口渴、尿频、体重减轻。"},
    ]

    myselfselector = MySelector(exs)
    select_examples = myselfselector.select_examples(input_variables={"ask1": ask})

    promt=""
    for ex in select_examples:
        promt = promt+ex['input']+":" + ex["output"] + "\n"

    print("提示词:" + promt)

    llm = Tongyi()

    rs = llm.stream(promt)
    response = StreamingHttpResponse(bcd(rs), content_type="text/event-stream")
    response["Cache-Control"] = "no-cache"
    return response



